﻿using Castle.Core.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WJP.ComponentModel;
using WJP.Dependency;

namespace WJP
{
    public abstract class PluginBase
    {
        /// <summary>
        /// IOC管理器
        /// </summary>
        protected internal IIocManager IocManager { get; internal set; }

        /// <summary>
        /// 日志记录器
        /// </summary>
        public ILogger Logger { get; set; }

        /// <summary>
        /// 插件对应的程序集
        /// </summary>
        public Assembly Assembly
        {
            get { return GetType().Assembly; }
        }

        /// <summary>
        /// 插件的启动级别。
        /// <para>注意：索引号越小表示越快启动，UI的索引号应大于Domain的索引号</para>
        /// </summary>
        public virtual int SetupLevel
        {
            get
            {
                return (int)SetupLevelEnum.UI;
            }
        }

        protected PluginBase()
        {
            Logger = NullLogger.Instance;
        }

        /// <summary>
        /// 这个插件启动时调用的第一个事件
        /// </summary>
        public virtual void PreInitialize()
        {

        }

        /// <summary>
        /// 插件的初始化方法
        /// </summary>
        /// <param name="app"></param>
        public abstract void Initialize(IApp app);

        /// <summary>
        /// 这个插件启动时调用的最后一个方法
        /// </summary>
        public virtual void PostInitialize()
        {

        }

        /// <summary>
        /// 当应用程序退出时会调用这个方法
        /// </summary>
        public virtual void Shutdown()
        {

        }

        /// <summary>
        /// 判断类型是不是插件类
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsPlugin(Type type)
        {
            var typeInfo = type.GetTypeInfo();

            return
                typeof(PluginBase).IsAssignableFrom(type) &&
                typeInfo.IsClass &&
                !typeInfo.IsAbstract &&
                !typeInfo.IsGenericType;
        }

        /// <summary>
        /// 查找插件的直接相关插件(不包括给定插件<see cref="AppCorePlugin"/>)
        /// </summary>
        public static List<Type> FindDependedPluginTypes(Type pluginType)
        {
            if (!IsPlugin(pluginType))
            {
                throw new AppException("这个类型不是插件类型，插件必须继承自AppPlugin" + pluginType.AssemblyQualifiedName);
            }

            var list = new List<Type>();

            if (pluginType.GetTypeInfo().IsDefined(typeof(DependsOnAttribute), true))
            {
                var dependsOnAttributes = pluginType.GetTypeInfo().GetCustomAttributes(typeof(DependsOnAttribute), true).Cast<DependsOnAttribute>();
                foreach (var dependsOnAttribute in dependsOnAttributes)
                {
                    foreach (var dependedModuleType in dependsOnAttribute.DependedPluginTypes)
                    {
                        list.Add(dependedModuleType);
                    }
                }
            }

            return list;
        }

        /// <summary>
        /// 递归的查找依赖插件，包含给定的插件<see cref="AppCorePlugin"/>
        /// </summary>
        /// <param name="moduleType"></param>
        /// <returns></returns>
        public static List<Type> FindDependedPluginTypesRecursivelyIncludingGivenPlugin(Type moduleType)
        {
            var list = new List<Type>();
            AddPluginAndDependenciesRecursively(list, moduleType);
            list.AddIfNotContains(typeof(AppCorePlugin));
            return list;
        }

        /// <summary>
        /// 递归的添加插件的依赖插件
        /// </summary>
        /// <param name="plugins"></param>
        /// <param name="plugin"></param>
        private static void AddPluginAndDependenciesRecursively(List<Type> plugins, Type plugin)
        {
            if (!IsPlugin(plugin))
            {
                throw new AppException("这个类型不是插件类型，插件必须继承自AppPlugin" + plugin.AssemblyQualifiedName);
            }

            if (plugins.Contains(plugin))
            {
                return;
            }

            plugins.Add(plugin);

            var dependedPlugins = FindDependedPluginTypes(plugin);
            foreach (var dependedPlugin in dependedPlugins)
            {
                AddPluginAndDependenciesRecursively(plugins, dependedPlugin);
            }
        }
    }
}
